/**
 * get forecast data with a given event code
 * @param urlParameter, the url pattern for servlet
 * @param action, a sign variable for calling get forecast method
 * @param eventCode, specific event code for forecast 
 * @returns
 */
function getTypeForecast(urlParameter, action, eventCode) {
	var xhrArgs = {
            sync: true,
            url: urlParameter,
            content : {
            	requestAction: action,
            	event : eventCode
            },
            handleAs: "json",
    		error: function(error) {
    		}
    };
	return dojo.xhrPost(xhrArgs);
}

/**
 * getting events from DB
 * @param urlParameter, the url pattern for servlet
 * @param action, a sign variable for calling get event method
 * @returns, JSON object
 */
function getEvents(urlParameter, action) {
	var xhrArgs = {
            sync: true,
            url: urlParameter,
            content : {requestAction: action},
            handleAs: "json",
    		error: function(error) {
    		}
    };
	return dojo.xhrPost(xhrArgs);
}

/**
 * get a color string with a given index
 * @param index
 * @returns : color string
 */
function getChartColor(index) {
	var colorList = ["red", "orange", "yellow", "blue", "green", "purple", "brown", "azure", "darkblue", "darkgreen"];
	return colorList[index];
}
/**
 * Getting data from the JSON response string, creating a data list for each type
 * @param dataTable : hash tables which contains the pair of (x axis label name, y axis value)
 * @param xAxisLabels : a hash table which contains the mapping of x labels (e.g. value : 1, text : EPL)
 * @param ticketLv_Num : the total number of different ticket levels
 * @returns {Array} : an array of list of different categories' values
 */
function generateColumnData(dataTable, xAxisLabels, ticketLv_Num) {
	var allYSeries = [];
	
	//adding all the data list into a total series list
	for(var type in dataTable) 
		allYSeries.push(dataTable[type]);
	
	console.log(allYSeries);
	//setting the labels for the x axis
	for(var i = 0; i < ticketLv_Num; i++) {
		var tmp = {};
		tmp.value = i+1;
		tmp.text = String.fromCharCode('A' + i);
		xAxisLabels.push(tmp);
	}
	return allYSeries;
}

/**
 * generate data for line chart
 * @param dataList : a list of data with Capacity as ticket type
 * @returns {Array} : an array of line chart data
 */
function generateLineData(dataList) {
	var lineData = [];
	for(var i = 0; i < dataList.length; i++) {
		var tmp = {};
		tmp.x = i+1;
		tmp.y = dataList[i];
		tmp.value = dataList[i];
		tmp.text = dataList[i];
		tmp.tooltip = dataList[i];
		lineData.push(tmp);
	}
	return lineData;
}

/**
 * generate the labels for the x axis, the labels are the keys in ticket type table
 * @param ticketTypeTable : a hash table between ticket levels and sold data
 * @returns {Array} : an array contains the labels for x axis
 */
function generateXAxisLabels(ticketLevelTable) {
	var xLabels = [];
	var index = 1;
	for(var key in ticketLevelTable) {
		var tmp = {};
		tmp.value = index++;
		tmp.text = key;
		xLabels.push(tmp);
	}
	return xLabels;
}

function getYAxisData(ticketLevelTable) {
	var yData = [];
	for(var lv in ticketLevelTable) {
		yData.push(ticketLevelTable[lv]);
	}
	return yData;
}

/**
 * interpret the json string, save the data in json string into hash table.
 * The hash table will contain the data shown in the clustered column chart
 * @param dataTable : hash table saves the data for showing clustered columns
 * @param jsonStr : json string contains the original data
 * @returns {Number} : the maximum value of data, it will be a upper limit for clustered column chart
 */
function JSONToTable(dataTable, jsonStr) {
	var maxData = 0;
	for(var i = 0; i < jsonStr.items.length; i++) {
		var curr = jsonStr.items[i];
		if(curr.Ticket == "Sold")
			continue;
		var ticketLvs = {};
		//get the data of each ticket level
		for (var type in curr) {
			if(type == "Ticket")
				continue;
			ticketLvs[type] = curr[type];
			
			//recording the largest maximum data shown in the clustered columns
			if(maxData < curr[type])
				maxData = curr[type];
		}
		dataTable[curr.Ticket] = ticketLvs;
	}
	consolg.log(dataTable);
	return maxData;
}

/**
 * set the advanced properties of dojo chart
 * @param chart : an object of dojo chart
 * @isPie : a boolean variable which shows whether the chart is a pie chart
 * @chartId : the id of a chart, or its sub chart
 */
function customizeChart(chart, isPie, chartId) {
    new dojox.charting.action2d.Tooltip(chart,chartId);
    new dojox.charting.action2d.Highlight(chart,chartId);
     
	if(isPie) 
		new dojox.charting.action2d.MoveSlice(chart,chartId);
	else
		new dojox.charting.action2d.Magnify(chart,chartId);	
}

/**
 * create a legend for a chart
 * @param chart : an object of chart
 * @param legendId : id of legend
 */
function generateLegend(chart, legendId) {
	var widget = dijit.byId(legendId);
	if(widget)
		widget.destroy();
	new dojox.charting.widget.Legend({chart: chart}, legendId);
}

/**
 * created a clustered column chart to show the data of different ticket types except "Capacity"
 * and created a line chart to show the data of "Capacity"
 */
function createClusteredColumns() {
	var deferred = getJSONData("/ActionController", "forecast");
	//use the JSON data to generate the graph
	deferred.then(function(res) {
		var ticketTypeTable = {};		//the hash table for each ticket type and its sold information of different ticket levels		
		var maxY = JSONToTable(ticketTypeTable, res) + 100;
		
		//get the labels for x axis
		var xAxisLabels = generateXAxisLabels(ticketTypeTable["Capacity"]);
//		var xAxisLabels = generateXAxisLabels(ticketTypeTable[res.items[0].Ticket].length);
		//create chart and set its x and y axis, also specify its theme
		var chart = new dojox.charting.Chart2D("chartTwo");
		
	    
		chart.addAxis("x", {labels : xAxisLabels});
	   // chart.addAxis("x", {majorLabels: true, majorTicks: true, majorTick: {length:1}, minorLabels: false, microTicks : false, labels : xAxisLabels});
	    chart.addAxis("y", {vertical: true, includeZero: false, fixLower: "major", fixUpper: "major", from: 0, to: maxY+maxY/100, majorTick: {color: "black", length: 6}, minorTicks: true, microTickes : true});
	    
	    //add a clustered column chart into plot
	    chart.addPlot("default", {type: "ClusteredColumns", tension: "S", shadows: {dx: 2, dy: 2}, gap: 2, minBarSize : 4, maxBarSize:14, animate:  { duration: 1000, easing: dojo.fx.easing.linear} });
	    
	    var counter = 0;
		//populate the data into columns
		for(var type in ticketTypeTable) {
			if(type == "Sold")
				continue;
			chart.addSeries(type, getYAxisData(ticketTypeTable[type]), {fill: getChartColor(counter)});
			counter++;
		}

		//add a line chart into plot
		//populate the capacity data into the line plot
	    chart.addPlot("Sold", { type: "Lines", markers: true});
	    
	    var lineData = generateLineData(getYAxisData(ticketTypeTable["Sold"]));
	    chart.addSeries("Sold", lineData, { plot: "Sold" });
	    chart.setTheme(dojox.charting.themes.Tom);
	    
	    customizeChart(chart, false, "default");
	    customizeChart(chart, false, "Sold");
        	
	    //render the chart and legend
	    chart.render();
	    generateLegend(chart, "legendTwo");
	});
}


/**
 * get the data for the y axis in column chart and the labels for the x axis
 * @param dataTable : hash tables which contains the pair of (x axis label name, y axis value)
 * @param xAxisLabels : a hash table which contains the mapping of x labels (e.g. value : 1, text : EPL)
 * @returns {Array} : an array of data in y axis
 */
function generateColumnData(dataTable, xAxisLabels, yAxis) {
	var maxY = 0;
	var counter = 1;
	for(var key in dataTable) {
		if(dataTable[key] > 0) {
			var tmp = {};
			tmp.value = counter;
			tmp.text = key;
			xAxisLabels.push(tmp);
			if(dataTable[key] > maxY)
				maxY = dataTable[key];
			var yTmp = {};
			yTmp.y = dataTable[key];
			if(yTmp.y > 0)
				yTmp.fill = getChartColor(counter-1);
			yAxis.push(yTmp);
			counter++;
		}
	}
	return maxY;
}

/**
 * Get the (x, y) data pairs for showing the pie chart
 * @param dataTable : hash tables which contains the pairs of (x, y) (e.g. x : ticket_level, y : sold total amount)
 * @param omittedKey, the word that will be omitted
 * @returns {Array} : a list of hashmap [{x : xValue1, y : yValue1}, {x : xValue2, y : yValue2}]
 */
function generatePieData(dataTable, omittedKey) {
	var dataItems = [];
	var counter = 0;
	for(var key in dataTable) {
		if(key == omittedKey)
			continue;
		if(dataTable[key] > 0) {
			var tmp = {};
			tmp.x = key;
			tmp.legend = key;
			tmp.y = dataTable[key];
			tmp.tooltip = key;
			tmp.color = getChartColor(counter); 
			dataItems.push(tmp);
			counter++;
		}
	}
	return dataItems;	
}

/**
 * create a column chart, its data relates with selection of combo box
 * @param type : selection of combo box
 * @param dataTable : hash table which contains the data for each price level
 */
function createColumnChart(type, dataTable) {
	var chart = new dojox.charting.Chart2D("chartTwo");
	//get the labels for x axis
	var xAxisLabels = [];
	var yAxis = [];
	var maxY = generateColumnData(dataTable, xAxisLabels, yAxis) + 100;
	
	chart.addAxis("x", {majorLabels: true, majorTicks: true, majorTick: {length:1}, minorLabels: false, microTicks : false, labels : xAxisLabels, fill : "black"});
    chart.addAxis("y", {vertical: true, includeZero: true, fixLower: "major", fixUpper: "major", from: 0, to: maxY, majorTick: {color: "black", length: 6}, minorTicks: true});
    
    //add a clustered column chart into plot
    chart.addPlot("default", {type: "Columns", tension: "S", shadows: {dx: 2, dy: 2}, gap: 2, minBarSize : 14, maxBarSize:24, animate:  { duration: 1000, easing: dojo.fx.easing.linear} });
      
	//populate the data into columns
    chart.addSeries(type, yAxis);
    var theme = dojox.charting.themes.Tom;
    theme.chart.fill= "lightgrey";
    theme.plotarea.fill = "lightgrey";
    chart.setTheme(theme);
    customizeChart(chart, false, "default");
    	
    //render the chart and legend
    chart.render();
    
    //generateLegend(chart, "legendThree");
}

/**
 * create a pie chart, its data relate with selection of combo box
 * @param type : selection of combo box
 * @param dataTable : hash table which contains the data for each price level
 */
function createPieChart(type, dataTable) {
		
	var chart = new dojox.charting.Chart2D("chartThree");
	//get the labels for x axis
	var dataItems = generatePieData(dataTable, "Total_Seats");
	
	chart.addPlot("default", {
    	type: "Pie",
    	labelOffset: -30,
    	radius: 150,
    	labelWiring: "grey",
        labelStyle: "columns",
        htmlLabels: true,
        plotarea: { fill: "#000" },
    	markers: true,
    	fontColor: "black"
	});
    
	//populate the data into columns
    chart.addSeries(type, dataItems);
    var theme = dojox.charting.themes.Tom;
    theme.chart.fill= "lightgrey";
    theme.plotarea.fill = "lightgrey";
    chart.setTheme(theme);
    
    customizeChart(chart, true, "default");
    //render the chart and legend
    chart.render();
    generateLegend(chart, "legendFour");
    //generateLegend(tmpChart, "legendThree");
}

/**
 * create the data for charts to show according to selection of combo box
 * @param res : json response string sent from servlet
 * @param type : selection of combo box
 * @returns {___anonymous9530_9531} : hash table which contains the data for each ticket level
 */
function getChartDataByType(res, type) {
	var dataTable = {};
	for(var i = 0; i < res.items.length; i++) {
		var curr = res.items[i];
		if(curr.Ticket != type)
			continue;
		for(var key in curr) {
			if((key == "Ticket") || (key == "Amount"))
				continue;
			dataTable[key] = curr[key];
		}
	}
	return dataTable;
}

function hasData(dataTable) {
	for(var key in dataTable) {
		if(dataTable[key] != 0) {
			return true;
		}
	}
	return false;
}

/**
 * create the chart according to selection of combo box
 * @param type : selection of combo box
 * @param eventCode, the event code for forecasting
 */
function createChartByType(type, eventCode) {
	var deferred = getTypeForecast("/msgSp12/ActionController", "forecastGraph", eventCode);
	deferred.then(function(res) {
		var dataTable = getChartDataByType(res, type);
		createColumnChart(type, dataTable);
		createPieChart(type, dataTable);
	});
}